﻿using UnityEngine;
using System.Collections;

public class BoundInScreen : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		//1
		Vector3 newPosition = transform.position;
		Camera mainCamera = Camera.main;
		Vector3 cameraPosition = mainCamera.transform.position;

		//2
		float xDist = mainCamera.aspect * mainCamera.orthographicSize; 
		float xMax = cameraPosition.x + xDist;
		float xMin = cameraPosition.x - xDist;

		float yDist = mainCamera.orthographicSize;
		float yMax = cameraPosition.y + yDist;
		float yMin = cameraPosition.y - yDist;

		if ( newPosition.x < xMin || newPosition.x > xMax ) {
			newPosition.x = Mathf.Clamp( newPosition.x, xMin, xMax );
		}

		if ( newPosition.y < yMin || newPosition.y > yMax ) {
			newPosition.y = Mathf.Clamp( newPosition.y, yMin, yMax );
		}
		transform.position = newPosition;
	}
}







